package com.youyun56.gps.schedual;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import org.apache.log4j.Logger;

import com.youyun56.pojo.Car;

public class GPSWriter implements Runnable {

    private LinkedBlockingQueue<Car> queue;
    private final static Logger logger = Logger.getLogger(GPSWriter.class);
    ByteBuffer buffer = ByteBuffer.allocate(8 * 1024);
    private StringBuffer sb = new StringBuffer();
    private Selector selector;
    private SocketChannel client;
    private Semaphore mutex;
    private Boolean run = true;

    public GPSWriter(LinkedBlockingQueue<Car> queue, SocketChannel client, Semaphore sem, Selector selector) throws IOException, GPSLoginException {
        this.selector = selector;
        this.queue = queue;
        this.client = client;
        this.mutex = new Semaphore(1);
        boolean success = false;
        _FOR: for (;;) {
            selector.select();
            Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
            while (iter.hasNext()) {
                SelectionKey key = iter.next();
                iter.remove();
                if (key.isConnectable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    if (channel.isConnectionPending()) {
                        channel.finishConnect();
                    }
                    channel.write(GPS.encoder.encode(CharBuffer.wrap(GPSFactory.login.toString())));
                    channel.register(selector, SelectionKey.OP_READ);
                    logger.info("connect over");
                } else if (key.isReadable()) {
                    logger.info("Reading...");
                    SocketChannel channel = (SocketChannel) key.channel();
                    int count = channel.read(buffer);
                    logger.info("start read");
                    if (count > 0) {
                        buffer.flip();
                        String line = null;
                        sb.append(new String(buffer.array()));
                        while ((line = MessageAnalysis.line(sb)) != null) {
                            logger.info("MSG: " + line);
                            if (MessageAnalysis.loginSuccess(line)) {
                                success = true;
                                channel.register(selector, SelectionKey.OP_WRITE);
                                break _FOR;
                            }
                        }
                        channel.register(selector, SelectionKey.OP_READ);
                        buffer.clear();
                    } else {
                        client.close();
                        success = false;
                        break _FOR;
                    }

                }
            }
        }
        if (!success) {
            throw new GPSLoginException();
        }

    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        logger.info(Thread.currentThread().getName() + " WRITER START SUCCESS");
        while (GPS.status == ServiceStatusType.active && run) {
            try {
                logger.info("acquire");
                logger.info(client.socket().isConnected());
                mutex.acquire();
                logger.info("acquired");
                selector.select();
                logger.info("selected");
                Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                while (iter.hasNext()) {
                    SelectionKey key = iter.next();
                    iter.remove();
                    if (key.isWritable()) {
                        SocketChannel channel = (SocketChannel) key.channel();
                        Car car = queue.take();
                        logger.info(String.format("Remainn %d cars", queue.size()));
                        GPS.currentCars.put(client, car);
                        channel.write(GPS.encoder.encode(CharBuffer.wrap(GPSFactory.gps(car.getCarMobile()))));
                        logger.info(String.format("Request Mobile %s", car.getCarMobile()));
                        if (!GPS.readers.isTerminating() && !GPS.readers.isShutdown()) {
                            GPSReader reader = new GPSReader(this.mutex, this.selector, this.client, this);
                            // logger.info("Start reader thread");
                            channel.register(selector, SelectionKey.OP_READ);
                            Future<?> future = GPS.readers.submit(reader);
                            GPS.tracerMapper.put(future, reader);

                        } else {
                            logger.warn("reader is shutdown");
                        }
                    }
                }

            } catch (InterruptedException e) {
                // e.printStackTrace();
                logger.error("InterruptedException",e);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                // e.printStackTrace();
                logger.error("IOException",e);
                break;
            } catch (NullPointerException e) {
                // TODO Auto-generated catch block
                // e.printStackTrace();
                logger.error("NullPointerException",e);
                break;
            }
        }
        logger.info("The Socket is Closed,Try to Recreate");
        while (true) {
            try {
                SocketChannel client = SocketChannel.open();
                // 设置为非阻塞模式
                client.configureBlocking(false);
                // 打开选择器
                Selector selector = Selector.open();
                // 注册连接服务端socket动作
                client.register(selector, SelectionKey.OP_CONNECT);
                // 连接
                client.connect(GPS.target);
                GPS.writers.submit(new GPSWriter(GPS.cars, client, new Semaphore(1), selector));
                break;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                // e.printStackTrace();
                logger.error("socket write exception",e);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    // e1.printStackTrace();
                    logger.error("Thread sleep Exception",e1);
                }
            }
        }

    }

    public Boolean getRun() {
        return run;
    }

    public void setRun(Boolean run) {
        this.run = run;
    }

    public Selector getSelector() {
        return selector;
    }

    public void setSelector(Selector selector) {
        this.selector = selector;
    }

    public static void main(String[] args) {
        String a = "dfwefe" + GPSFactory.line + "dfwfe";
        System.out.print(a.substring(0, a.indexOf(GPSFactory.line) + GPSFactory.line.length()));
    }

}
